import React from "react";
import {Button,Input} from 'fly';
import {Checkbox,message,DatePicker} from 'antd';
const{RangePicker} = DatePicker;
import Relay from 'react-relay';

import Header from './component/Logic_header';
import Logic_chartTransverse from './component/Logic_chartTransverse';
import Logic_Task from './component/Logic_Task';
import VariableGraph from './component/VariableGraph';
import View_IllustrDescribe from './component/View_IllustrDescribe';

import queryOrderIdMutation from './mutation/listOrderMutation';
import ListWorkGroupProInfoMutation from '../mutation/listWorkGroupProInfoMutation';

import {dateFormat,differenceDate} from './utils';

import "./style.scss";

export default class CreateProduction extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dateArr: [],  //本地时间列表
            isShowGroup:false,  //是否显示选择班组
            chooseGroupData:null,  //选择班组数据
            startDate:null, //开始时间
            endDate:null,  //结束时间
            orderList:[], //订单列表
            orderActive:null,  //选中的订单号
            styleNoActive:null, //选中的款号
            contractNumber:null, //合同数量
            textMinute:null,   //一个人的缝工时
            goodsDate:null,     //货期
        }
    };

    componentWillMount(){

    }

    componentDidMount(){
        // 请求首屏数据
        this.httpRequest(
            new queryOrderIdMutation({
                enId:sessionStorage.getItem("enterpriseId")
            }),
            (res)=>{
                const data = res.queryOrderId.queryOrderId;
                if(data.errorCode === "0"){
                    this.setState({ orderList:data.orders || [] })
                }else{ this.messageErrorCode(data.errorCode) }
            }
        );
    }

    //错误提示
    messageErrorCode(errorCode){
        console.log(errorCode);
        if(errorCode === "500"){
            message.error("服务器错误，请联系系统管理员");
        }
    }

    //选择班组(触发)
    chooseGroupTrigger = ()=>{
        // 验证
        // 请求数据
        this.httpRequest(
            new ListWorkGroupProInfoMutation({
                enterpriseId:sessionStorage.getItem("enterpriseId"),
                startDate:this.state.startDate,
                endDate:this.state.endDate,
            }),
            (res)=> {
                const data = this.chooseGroupDataFormatt(res);

                this.setState({isShowGroup: true, chooseGroupData: data})
            }
        );
    };

    //班组数据格式整理
    chooseGroupDataFormatt = (res)=>{
        res = res.listWorkGroupProInfo.listWorkGroupProInfo;
        res.stylePlanReports = JSON.parse(res.stylePlanReports);
        for(let i in res.stylePlanReports){
            res.stylePlanReports[i] = JSON.parse(res.stylePlanReports[i])
        }
        const data = {proWorkGroupList:res.proWorkGroupList,stylePlanReports:res.stylePlanReports};
        return data;
    };

    //请求数据
    httpRequest(inParamMutation,cb){
        Relay.Store.commitUpdate(
            inParamMutation,
            {
                onFailure:()=>{
                    message.error("网络请求失败");
                },
                onSuccess:(res)=>{
                    cb(res);
                }
            }
        )
    };

    // 只负责更新本地dateArr
    startPlanDateChange = ([startDate,endDate])=>{

        let d = new Date(startDate._d);  //开始时间
        let d_end = new Date(endDate._d);    //结束时间

        let dateArr = [];

        if( (d_end - d)/1000/60/60/24 < 30 ){
            d_end.setMonth(d.getMonth() + 1);
        }

        // 更新时间数组取出90天中的时间列表
        while(1) {
            if (d.valueOf() > d_end.valueOf()) { break;}

            dateArr.push(dateFormat(d));  // dateArr :: ["2017-05-05","2017-05-06"......]

            d.setDate(d.getDate() + 1);  //  自增1天
        }

        this.setState({
            dateArr,
            startDate:dateFormat(startDate._d),
            endDate:dateFormat(endDate._d)
        })
    };

    //多选班组change
    groupCheckboxChange(i){
        console.log(i);
    }

    //创建
    handleCreateClick(){}

    /**
     * @param type 分辨类型
     * @param e change 参数
     * @param addIn 额外参数
    * */
    orderListStyNoChange = (type,e,addIn)=>{
        switch(type){
            case "order" : {
                if(e !== this.state.orderActive){
                    this.filterGoodsDate(e,addIn);
                    this.setState({
                        orderActive:e,
                        styleNoActive:null,
                        contractNumber:null,
                    });
                }
                return;
            }
            case "styleNo" : {
                this.setState({styleNoActive:e,contractNumber:this.filterContractNumber(e,addIn)});
                return;
            }
        }
    };

    //根据款号筛选合同数量
    filterContractNumber(styleNo,orderGoodss){
        const o = orderGoodss.filter((item)=>{
            return item.styleNo === styleNo
        });
        return o[0].quantity
    }

    //根据订单号导出款号的列表
    filterStyleNo = (list,active)=>{
        let o = list.filter((item)=>{
            return item.oid === active;
        });
        if(o[0]){
            return o[0].orderGoodss;
        }
        return [];
    };

    //根据订单号导出货期
    filterGoodsDate = (orderId,list)=>{
        const o = list.filter((item)=>{
            return item.oid === orderId
        });

        if(o[0]){
            this.setState({goodsDate:o[0]})
        }
    };

    textMinuteChange = (e)=>{
        const text = e.target.value;
        const reg = /\D/;

        if(reg.test(e.target.value)){ return; }

        this.setState({ textMinute:e.target.value });
    };

    render() {
        const {
            dateArr, //本地时间列表
            isShowGroup,  //是否显示班组信息
            chooseGroupData,  //班组信息
            orderList,       //订单列表
            startDate,     //开始时间
            orderActive,  //选中的订单号
            styleNoActive,  //选中的款号
            contractNumber,  //合同数量
            textMinute,  //一个人的缝工时
            currentGoodsDate,  //当前货期
        } = this.state;

        const groupRender = ()=>{

            const proWorkArr = chooseGroupData.proWorkGroupList || [];
            const stylePlanArr = chooseGroupData.stylePlanReports || {};

            return (
            <div data-type="main">
                <div className="Yyd-chart">
                    <div data-type="choose">
                        <ul>
                            <li> 班组 </li>
                            {
                                proWorkArr.map((item,index)=>
                                    <li>
                                        <Checkbox onChange={this.groupCheckboxChange}>
                                            {`${item.workShopName}${item.workGroupId}組`}
                                        </Checkbox>
                                    </li>
                                )
                            }
                        </ul>
                    </div>
                    <div data-type="content">
                        <Logic_chartTransverse
                            dateArr={dateArr}
                            canvasStartDate={startDate}  //开始的时间
                            data={stylePlanArr["5"]}
                        />
                    </div>
                </div>
                <View_IllustrDescribe />
            </div>
            )
        };

        return (<div className="create_Production">
                {/*header控制台*/}
                <Header
                    orderListStyNoChange={this.orderListStyNoChange}  //订单下拉框与款号的change事件

                    styleNoActive={styleNoActive}  //选中的款号
                    orderList={orderList}  //订单列表
                    orderGoodss={this.filterStyleNo(orderList,orderActive)}  //选中的订单对应的款号列表
                    contractNumber={contractNumber}  //合同数量
                >
                    <div>
                        <div className="create_Production_headerItem" data-necessary="true">
                            <span data-type="title">
                            每件成衣的一人车缝工时
                            <Input  style={{width:62,margin:"0 10px",textAlign:"center"}}
                                    value={textMinute}
                                    size="small"
                                    onChange={this.textMinuteChange}
                            />
                                分钟
                            </span>
                        </div>

                        <div className="create_Production_headerItem" data-necessary="true">
                            <span data-type="title"> 计划开始时间 :</span>
                            <RangePicker
                                style={{ width: 220 }}
                                onChange={this.startPlanDateChange}
                            />
                        </div>

                        <div className="create_Production_headerItem">
                            <span data-type="title"> 货期 {currentGoodsDate} </span>
                        </div>
                    </div>
                </Header>

                {/*设置平均产量*/}
                <div className="create_Production_average">
                    <div data-type="header">
                        <div className="create_Production_headerItem" data-necessary="true">
                            <span data-type="title">设置平均产量(调整产能爬坡的结束点):</span>
                        </div>
                        <Button > 设置平均产量 </Button>
                    </div>
                    <VariableGraph />
                </div>

                {/*选择班组*/}
                <div className="create_Production_group">
                    <div data-type="header">
                        <div className="create_Production_headerItem" data-necessary="true">
                            <span data-type="title"> 选择班组 :</span>
                        </div>
                        <Button onClick={this.chooseGroupTrigger}> 选择班组 </Button>
                    </div>
                    {
                        isShowGroup && groupRender()
                    }
                </div>

                {/*任务分配*/}
                <div className="create_Production_taskDis">
                    <div data-type="header">
                        <div className="create_Production_headerItem" data-necessary="true">
                            <span data-type="title"> 任务分配 :</span>
                        </div>
                    </div>
                    <div data-type="create_Production_taskDis_main">
                        <Logic_Task />
                    </div>
                </div>

                {/*创建*/}
                <footer className="create_Production_footer">
                    <Button onClick={this.handleCreateClick}>
                        创建
                    </Button>
                </footer>
            </div>
        )
    }
}